import './App.scss'
import 'bootstrap/dist/css/bootstrap.css'
import Head from "./components/head/index";
import Item from "./components/item";
import Foot from "./components/foot";

import request from "./utils/request";
import { useEffect, useState } from 'react'
import { CountContext } from './utils/myContext' 
export default function App () {
  const [list,setList]=useState([])
  useEffect(()=>{
    (async()=>{
      const{data:{list}}=await request.get('/api/cart')
      console.log(list);
      setList(list)
    })()
  },[])
  // 修改商品选中的方法
  const changeSel=(goods_id,goods_state)=>{
    setList(
      list.map((item)=>{
        if (item.goods_id===goods_id) {
          return{
            ...item,
            goods_state
          }
        }
        return item
      })
    )
  }
  // 修改商品数量
  const changeCount=(goods_id,goods_count)=>{
    setList(
      list.map((item)=>{
        if (item.goods_id===goods_id) {
          return{
            ...item,
            goods_count
          }
        }
        return item
      })
    )
  }
  const totalCount = list.reduce((count, item) => {
    if (item.goods_state) {
      return count + item.goods_count
    }
    return count
  }, 0)
  
  const totalPrice = list.reduce((count, item) => {
    if (item.goods_state) {
      return count + item.goods_count * item.goods_price
    }
    return count
  }, 0)
  return (
    <CountContext.Provider value={{changeCount}}>
    <div className="app">
      {/* 标题 */}
      {/* <div className="my-header">购物车</div> */}
      <Head></Head>

      {/* 商品列表项 */}
      {
        list.map((item)=>
        // <Item key={item.id} good={item}/>
        <Item changeSel={changeSel} key={item.goods_id} {...item}></Item>
        )
      }
      

      {/* 底部 */}
      <Foot totalCount={totalCount} totalPrice={totalPrice}></Foot>
    </div>
    </CountContext.Provider>
  )
}
